#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   __init__.py
@Time    :   2024-07-09 13:01:25
@Author  :   chakcy 
@Email   :   947105045@qq.com
@description   :   redis依赖
'''
from datetime import datetime

import aioredis
from fastapi import Depends

from app.config import config
from .hash import Hash
from .item import Item
from .list import List
from .set import Set
from .sorted_set import SortedSet
from .pub_sub import PubSub

redis_conf = config.redis

async def get_redis_conn():
    """获取 Redis 连接"""
    if redis_conf.password != '':
        url = f"redis://:{redis_conf.password}@{redis_conf.host}:{redis_conf.port}/0"
    else:
       url = f"redis://{redis_conf.host}:{redis_conf.port}/0"
    redis = aioredis.from_url(url, encoding='utf-8', decode_responses=True) 
    try:
        yield redis
    finally:
        await redis.close()

class RedisDependency:
    """Redis 依赖"""
    def __init__(self, redis: aioredis.Redis = Depends(get_redis_conn)):
        # 初始化 Redis 连接
        self.redis = redis
    
    def pipeline(self):
        """返回 Redis Pipeline 实例"""
        return self.redis.pipeline()
    
class RedisOperation:
    """Redis 操作"""
    def __init__(self, redis: aioredis.Redis):
        self.redis = redis

    def expire(self, key:str, time:int):
        """设置 key 的过期时间"""
        return self.redis.expire(key, time) 
    
    def expireat(self, key:str, timestamp:datetime):
        """设置 key 过期时间"""
        unix_timestamp = int(timestamp.timestamp())
        return self.redis.expireat(key, unix_timestamp) 

    def item(self) -> Item:
        """返回 Item 实例"""
        return Item(self.redis)
    
    def hash(self) -> Hash:
        """返回 Hash 实例"""
        return Hash(self.redis)

    def list(self) -> List:
        """返回 List 实例"""
        return List(self.redis)
    
    def set(self) -> Set:
        """返回 Set 实例"""
        return Set(self.redis)
    
    def sorted_set(self) -> SortedSet:
        """返回 SortedSet 实例"""
        return SortedSet(self.redis)

    def pub_sub(self) -> PubSub:
        """返回 PubSub 实例"""
        return PubSub(self.redis)
    
__all__ = ["RedisDependency", "RedisOperation"]